const { verifyToken, generateToken } = require("../utils/jwt");
const auth = async (ctx, next) => {
    if (ctx.headers.authorization) {
        const token = ctx.headers.authorization.split(" ")[1] || "";
        if (verifyToken(token)) {
            // 验证通过，重新生成token，保持登录状态
            const { _id, username } = verifyToken(token);
            ctx.set("Authorization", generateToken({ _id, username }));
            await next();
        } else {
            ctx.status = 401;
            ctx.body = {
                code: 401,
                msg: "token已过期",
                data: null,
            };
        }
    } else {
        ctx.status = 401;
        ctx.body = {
            code: 401,
            msg: "token不存在",
            data: null,
        };
    }
};

module.exports = auth;
